<template>
  <cube-page type="button-view" title="采购项目列表" @rightBtnClick="zfilterDrawer" :rightBtn="true">
    <div slot="content">
      <cube-tab-bar v-model="selectedLabel" show-slider @change="changeHandler">
        <cube-tab v-for="(item, index) in tabs" :label="item" :key="index"></cube-tab>
      </cube-tab-bar>

      <div class="scroll-list-wrap" :style="{'height': getlistHeight}">
        <cube-scroll ref="scroll" :data="tableData" :options="options" @pulling-down="onPullingDown" @pulling-up="onPullingUp">
          <div class="zcardWrap">
            <div class="zcard" v-for="(v, index) in tableData" :key="index" @click="goDetail(v, index, $event)">
              <div class="zui-flex zcardRow zheader">
                <div class="zlabel">{{index+1}}. {{v.name}}</div>
              </div>
              <!--
              <div class="zui-flex zcardRow">
                <div class="zlabel">状态</div>
                <div class="zdes">
                  <span v-if="v.status == 0" class="zui_done">已完成</span>
                  <span v-if="v.status == 1" class="zui_new">已拒绝</span>
                  <span v-if="v.status == 2" class="zui_doing">进行中</span>
                  <span v-if="v.status == 3" class="zui_undo">未处理</span>
                </div>
              </div>
              -->
              <div class="zui-flex zcardRow">
                <div class="zlabel">标签</div>
                <div class="zdes ztagWrap">
                  <span class="ztag" :class="'ztag_'+tag.type" v-for="(tag, indexS) in v.tags" :key="indexS">
                    {{tag.name}}
                  </span>
                </div>
              </div>
              <div class="zui-flex zcardRow">
                <div class="zlabel">视频</div>
                <div class="zdes">
                  <span class="videoBtn" @click="playVideo(v, index)">点击播放</span>
                </div>
              </div>
              <div class="zui-flex zcardRow" v-if="v.area && v.area.length" v-for="(m,n) in v.area" :key="n">
                <div class="zlabel" v-if="n==0">高毛利区域</div>
                <div class="zdes">{{m.name}} ({{m.value}})</div>
              </div>
              <!--
              <div class="zui-flex zcardRow zcardBtns" v-if="v.status != 1">
                <template v-if="v.status == 0 || v.status == 2">
                  <cube-upload
                    ref="upload"
                    v-model="files"
                    :action="action"
                    @files-added="addedHandler(v, index)"
                    @file-success="successHandler"
                    @file-error="errHandler">
                    <div class="clear-fix">
                      <cube-upload-btn :multiple="false">
                        <cube-button :primary="true" class="zbtn zuiReplayBtn one">上传证据</cube-button>
                      </cube-upload-btn>
                    </div>
                  </cube-upload>
                </template>
                <template v-if="v.status == 3">
                  <cube-button class="zbtn" @click="zfavorites(v, false)">拒绝</cube-button>
                  <cube-button :primary="true" class="zbtn zuiReplayBtn" @click="zfavorites(v, true)">接收</cube-button>
                </template>
              </div>
              -->
            </div>
          </div>
        </cube-scroll>
      </div>

      <drawer :show="drawerShow" @change-show="changeDrawerShow" @on-hide="onHide" @on-show="onShow">
        <div class="zuiDrawerWrap" slot="drawer">
          <div class="zrow">
            <div class="zlabel">项目名</div>
            <div class="zdes">
              <cube-input class="zinput" v-model="searchOut.name" placeholder="请输入项目名"></cube-input>
            </div>
          </div>

          <div class="zrow">
            <div class="zlabel">标签名</div>
            <div class="zdes">
              <cube-input class="zinput" v-model="searchOut.bq" placeholder="请输入标签名"></cube-input>
            </div>
          </div>

          <div class="zui-flex btn-area">
            <cube-button class="zbtn J_reset" @click="zreset">重置</cube-button>
            <cube-button class="zbtn J_sub" @click="zsubmit">提交</cube-button>
          </div>

        </div>
      </drawer>

      <router-view></router-view>
      <cube-popup type="zuipopup" ref="zuipopup" @mask-click="hidezpop">
        <div class="zpopupWrap uni-tip">
          <video-player class="video-player vjs-custom-skin"
            ref="videoPlayer"
            :playsinline="playsinline"
            :options="playerOptions"
            @ready="playerReadied"
            @statechanged="playerStateChanged($event)"
            @fullscreenchange="fullscreenchange"
            @ended="palyerended"
          ></video-player>
        </div>
      </cube-popup>
    </div>
  </cube-page>
</template>

<script>
import {
  mapState,
  mapGetters,
  mapMutations,
  mapActions
} from 'vuex'

import BusFactory from 'vue-happy-bus';
import CubePage from '@/components/cube-page'
import CubeView from '@/components/cube-view'
import Drawer from '@/components/drawer'
import {zProjectList, zProjectListRec} from '@/util/api';

import 'video.js/dist/video-js.css'
import 'vue-video-player/src/custom-theme.css'
// import { videoPlayer } from 'vue-video-player'
import {videoPlayer} from '@/components/zvideo/index.js'

export default {
  name: 'Forecast',
  components: {
    CubeView,
    CubePage,
    Drawer,
    videoPlayer
  },
  computed: {
    ...mapState(['loginUserInfo']),
    playsinline () {
      let ua = navigator.userAgent.toLocaleLowerCase()
      // x5内核
      if (ua.match(/tencenttraveler/) != null || ua.match(/qqbrowse/) != null) {
        return false;
      } else {
        // ios端
        return true;
      }
    },
    zplayerObj () {
      return this.$refs.videoPlayer.player
    }
  },
  data () {
    return {
      bus: BusFactory(this),
      showLoading: true,
      tableData: [],
      total: 0,
      start: 1,
      pageSize: 5,
      pullDownRefreshThreshold: 60,
      pullDownRefreshStop: 40,
      options: {
        pullDownRefresh: {
          threshold: 60,
          txt: '正在刷新...'
        },
        pullUpLoad: {
          threshold: 60,
          txt: {
            more: '上拉加载更多',
            noMore: '没有更多数据了...'
          }
        },
        scrollbar: true,
        click: true,
        tap: true,
        taps: true,
      },
      getlistHeight: this.zutil.getlistHeight(44),
      selectedLabel: '已完成',
      tabs: ['已完成', '已拒绝', '进行中', '未处理'],
      searchOut: {
        name: '',
        bq:'',
        status: 0
      },
      drawerShow: false,
      zuiPopObj: null,
      playerOptions: {
        // 视频播放
        playbackRates: [], //播放速度
        autoplay: false, //如果true,浏览器准备好时开始回放。
        muted: false, // 默认情况下将会消除任何音频。
        loop: false, // 导致视频一结束就重新开始。
        preload: 'auto', // 建议浏览器在<video>加载元素后是否应该开始下载视频数据。auto浏览器选择最佳行为,立即开始加载视频（如果浏览器支持）
        language: 'zh-CN',
        aspectRatio: '16:9', // 将播放器置于流畅模式，并在计算播放器的动态大小时使用该值。值应该代表一个比例 - 用冒号分隔的两个数字（例如"16:9"或"4:3"）
        fluid: true, // 当true时，Video.js player将拥有流体大小。换句话说，它将按比例缩放以适应其容器。
        sources: [{
          type: "",
          src: 'http://lx.huirenyy.com/cx/item1.mp4' //url地址
        }],
        poster: "", //你的封面地址
        // width: document.documentElement.clientWidth,
        notSupportedMessage: '此视频暂无法播放，请稍后再试', //允许覆盖Video.js无法播放媒体源时显示的默认信息。
        controlBar: {
          timeDivider: true,
          durationDisplay: true,
          remainingTimeDisplay: false,
          fullscreenToggle: true //全屏按钮
        }
      },
      action: {
        target: 'https://jsonplaceholder.typicode.com/photos/',
        data: {}
      },
      files: [],
      zuploadLoading: null,
      curUploadObj: null
    }
  },
  created () {

  },
  mounted() {
    this.zuiPopObj = this.$refs['zuipopup'];
    document.addEventListener('keyup', (e)=>{
      if (e.keyCode == 27) {
        this.hidezpop();
      }
    })
    this.searchData();
  },
  watch: {

  },
  methods: {
    ...mapMutations(['setW_shortageData']),
    isWeixinBrowser(){
      var ua = navigator.userAgent.toLowerCase();
      return (/micromessenger/.test(ua)) ? true : false ;
    },
    isPhoneBrowser(){
      var u = navigator.userAgent;
      return (!!u.match(/AppleWebKit.*Mobile.*/) || u.indexOf('iPad') > -1) ;
    },
    changeHandler (label) {
      let _index = this.tabs.findIndex(v=>v==label);
      this.searchOut.status = _index;
      this.searchData();
    },
    resetPage () {
      this.tableData = [];
      this.total = 0;
      this.start = 1;
    },
    onPullingDown() {
      // 下拉刷新
      this.resetPage();
      this.fetchList();
    },
    onPullingUp() {
      // 上拉加载更多
      if(this.total && this.tableData.length < this.total){
        this.fetchList();
      }else if(this.total && this.tableData.length == this.total){
        this.$refs.scroll.forceUpdate();
        return;
      }
    },
    searchData () {
      this.tableData = [];
      this.total = 0;
      this.$refs.scroll.scrollTo(0, 0, 500);
      this.start = 1;
      this.fetchList();
    },
    async fetchList () {
      let tbl_param = {
        name:this.searchOut.name,
        bq:this.searchOut.bq,
        page: this.start,
        pagesize: this.pageSize
      }
      this.zutil.deepClone(tbl_param, this.searchOut);

      const zuiCubeLoading = this.$createToast({time: 0,txt: '正在加载中...'});
      zuiCubeLoading.show();
      let res = await zProjectList(tbl_param);
      res = this.zutil.formatAxiosData(res);
      zuiCubeLoading.hide();

      if(res.code == '0000'){
        if(res.data.list && res.data.list.length){
          this.tableData = this.tableData.concat(res.data.list);
          this.total = res.data.total;
          this.start++;
        }else{
          this.$refs.scroll.forceUpdate();
        }
      }else{
        this.$createToast({type: 'error', time: 2000, txt: res.message || "获取缺货信息列表失败！"}).show();
        this.$refs.scroll.forceUpdate();
      }
      // 如果微信确实无法触发点击事件，再放开这段代码
      // this.zutil.initBtnsClickEvent(this, '.zuiReplayBtn', this.zreplay);
    },
    zfilterDrawer () {
      this.drawerShow = true;
    },
    drawerToggle () {
      this.drawerShow = !this.drawerShow;
    },
    onHide () {

    },
    changeDrawerShow (state) {
      // 在父页面点击mask关闭页面
      this.drawerShow = state;
    },
    onShow () {

    },
    zreset () {
      if(this.routeIndex == 0){
        this.searchOut = {
          bq: '',
          name: '',
          type: '1',
          sdate: '',
          edate: ''
        }
        if(this.datePicker)
          this.datePicker.$updateProps({value: new Date()});
        if(this.datePickeS)
          this.datePickerS.$updateProps({value: new Date()});
      }
    },
    zsubmit () {
      this.drawerShow = false;

      this.bus.$emit('pageRefresh', this.searchOut);
    },
    hidezpop () {
      try{
        this.zplayerObj.pause();
        this.zplayerObj.currentTime(0);
        this.zuiPopObj.hide();
      }catch(e){}
    },
    showZuiPop (item, type) {

       console.info(item.videoUrl);
      this.playerOptions['sources'][0]['src'] = item.videoUrl;


      const zuiCubeLoading = this.$createToast({time: 0,txt: '正在加载中...'});
      zuiCubeLoading.show();
      let times = 100,
        phoneFlag = this.isPhoneBrowser();
      if(phoneFlag)
        times = 1000;

      setTimeout(()=>{
        if(!phoneFlag){
          // 全屏
          this.zplayerObj.requestFullscreen();
        }
        this.zplayerObj.play();
        if(!this.isWeixinBrowser()){
          this.zuiPopObj.show();
        }
        zuiCubeLoading.hide();
      }, times)
    },
    goDetail (item, index, ev) {

        console.info("goDetail:"+JSON.stringify(item));
      let e = ev || window.event;
      let target = e.target || e.srcElement;
      if(target.classList.contains('videoBtn')){
        return false;
      }

      this.zutil.lStorage.setParam('lst_projectBaseInfo', JSON.stringify(item));
      // this.$router.push(`/projectS/projectInfoS`);   2020-06-19  xyg  修改  跳过中间页面
      this.$router.push(`/projectS/projectInfoS/projectdetailS`);
    },
    playVideo (item, index) {
      this.showZuiPop(item);
    },
    playerReadied (obj) {
    },
    playerStateChanged (ev) {
    },
    fullscreenchange () {
      if(!this.zplayerObj.isFullscreen()){
        this.hidezpop();
      }
    },
    palyerended () {
      if(this.zplayerObj.isFullscreen()){
        this.zplayerObj.exitFullscreen();
      }
      this.hidezpop();
    },
    addedHandler(item, index) {
      this.curUploadObj = item;
      this.action.data.id = item.id;
      this.zuploadLoading = this.$createToast({time: 0,txt: '正在加载中...'});
      this.zuploadLoading.show();
    },
    successHandler(file) {
      // 测试，需删
      file.response = {
        code: '0000'
      }
      this.zuploadLoading.hide();
      if(file.response.code == '0000'){
        this.$createToast({
          txt: '证据上传成功',
          type: 'correct'
        }).show();
      }else{
        this.$createToast({type: 'error', time: 2000, txt: file.response.message || "上传失败！"}).show();
      }
    },
    errHandler(file) {
      this.$createToast({type: 'error', time: 2000, txt: file.response.message || "上传失败！"}).show();
      this.zuploadLoading.hide();
    },
    zfavorites (item, flag) {
      let str = '拒绝';
      if(flag)
        str = '接收';
      this.$createDialog({
        type: 'confirm',
        icon: 'cubeic-warn',
        content: `是否确认${str}该项目？`,
        onConfirm: () => {
          this.favoritesAdd(item, flag);
        },
        onCancel: () => {}
      }).show()
    },
    async favoritesAdd (item, flag) {
      let str = '拒绝',
        newstatus = 1;
      // ['已完成', '已拒绝', '进行中', '未处理'],
      if(flag){
        str = '接收';
        newstatus = 0;
      }
      const zuiCubeLoading = this.$createToast({time: 0,txt: '正在加载中...'});
      zuiCubeLoading.show();
      let res = await zProjectListRec({id: item.id, status: flag});
      res = this.zutil.formatAxiosData(res);
      zuiCubeLoading.hide();
      this.$set(item, 'status', newstatus);
      if(res.code == '0000'){
        this.$createToast({type: 'correct', time: 2000, txt: res.message || `${str}该项目成功`}).show();
      }else{
        this.$createToast({type: 'error', time: 2000, txt: res.message || `${str}该项目失败`}).show();
      }
    }
  },
  beforeDestroy() {
    /*if (this.zplayerObj) {
      this.zplayerObj.dispose();
    }*/
  }
}
</script>

<style scoped lang="scss">

.cube-tab-bar {
  height: 44px;
  font-size: 13px;
  background: #fff;
  border-bottom: 1px solid #ddd;
  .cube-tab {

  }
}
.scroll-list-wrap .zcardWrap .zcard .zcardRow {
  .zlabel {
    width: 40px;
  }
  .zdes {
    &.ztagWrap {
      display: flex;
      justify-content: flex-end;
      .ztag {
        width: 60px;
        height: 25px;
        line-height: 25px;
        text-align: center;
        background: #ddd;
        margin-left: 5px;
        border-radius: 5px;
        font-size: 12px;
        color: #fff;

        &.ztag_1 {
          background: #909399;
        }
        &.ztag_2 {
          background: #409EFF;
        }
        &.ztag_3 {
          background: #67C23A;
        }
        &.ztag_4 {
          background: #E6A23C;
        }
        &.ztag_5 {
          background: #F56C6C;
        }
      }
    }

    .videoBtn {
      height: 35px;
      line-height: 35px;
      display: inline-block;
      width: 60px;
      .playicon {

      }
    }
  }
  &.zheader {
    height: 50px;
    line-height: 50px;

    .zlabel {
      flex: 1;
      color: #000;
      font-size: 15px;
    }
  }
}

.scroll-list-wrap .zcardWrap .zcard .zcardRow.zcardBtns {
  .cube-upload {
    width: 100%;
    .zbtn {

      &.one {
        border-bottom-right-radius: 0.16rem;
        background: #473c91;
      }
    }
  }
}
.zui_new {
  color: #ff0000!important;
}
.zui_undo {
  color: #be9a9a!important;
}
.zui_done {
  color: #28c488!important;
}
.zui_doing {
  color: #28c488!important;
}
</style>
